#!/usr/bin/env python

__version__ = '$Revision$'
# Last Modified on $Date$
# by $Author$
# from $Source$


import os
import sys
import subprocess
import datetime

import mutils
import googlecode_upload

project_name = 'mca09'
repo1 = os.path.join(os.getenv('SCRIPTS_DIR'), project_name)
#repo2 = '/media/mca_server/mca1/C_Programs'
repo2 = '/media/mca8/MCA09 C Programs'
gcode_url = 'https://dkmurthy9:%s@%s.googlecode.com/hg/' % (os.getenv('DKMURTHY_GOOGLECODE_PASSWD'), project_name)


def my_fetch(src, dest):
    """Fetch src to dest
    """
    print 'Syncing %s to %s' % (src, dest)
    os.chdir(dest)
    subprocess.call('hg fetch %s' % src, shell=True)

def my_commit(repo):
    print 'Committing changes in repo %s' % repo
    os.chdir(repo)
    subprocess.call('hg addremove -s 50', shell=True)
    subprocess.call('hg commit -m "auto-commit"', shell=True)

def upload_files(repo):
    os.chdir(repo)
    for dir in os.listdir(repo):
        if os.path.isdir(dir) and dir != '.hg':
            subprocess.call('zip -r %s %s' % (dir, dir), shell=True)
            googlecode_upload.upload_find_auth(dir + '.zip',
                                               project_name,
                                               'Programs by ' + dir,
                                               'Featured',
                                               'dkmurthy9',
                                               os.getenv('DKMURTHY_GOOGLECODE_PASSWD'))
            os.remove(dir + '.zip')




def main():

    if os.path.exists(repo1):
        my_commit(repo1)

    if os.path.exists(repo2):
        my_commit(repo2)

        # sync repo1 and repo2
        my_fetch(repo2, repo1)
        my_fetch(repo1, repo2)
        my_fetch(repo2, repo1)

    if mutils.online() and os.path.exists(repo1):
        my_fetch(gcode_url, repo1)
        print 'Pushing %s to %s' % (repo1, gcode_url)
        os.chdir(repo1)
        subprocess.call('hg push %s' % gcode_url, shell=True)

        if datetime.date.today().weekday() == 2:
            upload_files(repo1)


#The following code will be executed only if called as stand-alone script.
#Skipped if imported as module
if __name__ == "__main__":
    sys.exit(main())
